# coding=utf-8
import sys
import socket
from flask import Flask, request, redirect

app = Flask(__name__, static_folder='static', static_url_path="")


def wake_on_lan(mac_address):
    # 构建魔术包
    data = ''.join(['FF' * 6, mac_address.replace(':', '') * 16])
    # 将十六进制数据转换为二进制数据
    send_data = b''
    for i in range(0, len(data), 2):
        send_data += bytes.fromhex(data[i:i + 2])
    # 创建UDP套接字
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
    # 发送魔术包到广播地址
    sock.sendto(send_data, ('<broadcast>', 9))
    print("魔术包已发送")


@app.route('/api/onWake', methods=['GET', 'POST'])
def on_wake():
    mac_address = request.values.get('macAddress')
    print("mac地址：%s" % mac_address)
    wake_on_lan(mac_address)
    return_data = {"state": 0, "macAddress": mac_address}
    return return_data


@app.route('/')
def index():
    # 重定向到首页
    return redirect('index.html')


if __name__ == '__main__':
    args = sys.argv[1:]
    if len(args) == 0:
        # 默认端口54609
        args.append("54609")
    app.run(host="0.0.0.0", port=int(args[0]), debug=True)
